package com.allwees.bs.c.module.order.entity;

import com.allwees.bs.core.model.order.wf.order.EOrderState;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

public class OrderSpecification {
    private OrderSpecification() {

    }

    public static Specification<OrderEntity> specification(String userUuid, EOrderState[] state, Integer type) {

        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            predicates.add(cb.equal(root.<String>get("userUuid"), userUuid));

            if (state != null && state.length > 0) {
                List<Predicate> statePredicates = new ArrayList<>();
                for (EOrderState s : state) {
                    statePredicates.add(cb.equal(root.<Integer>get("state"), s));
                }
                Predicate[] statePredicatesArray = new Predicate[statePredicates.size()];
                predicates.add(cb.or(statePredicates.toArray(statePredicatesArray)));
            }

            if (type != null) {
                predicates.add(cb.equal(root.<Integer>get("type"), type));
            }
            Predicate[] pre = new Predicate[predicates.size()];
            return query.where(predicates.toArray(pre)).getRestriction();
        };
    }
}
